var stats = new Stats(),
    c = document.getElementById('c'),
    ctx = c.getContext('2d'),
    GRAVITY_FORCE = 9.81,
    CANVAS_HEIGHT_AS_METER = 10,
    pixelPerMeter = 0,
    fps;
window.addEventListener('resize', handleWindowResize, false);
function handleWindowResize () {
    c.width = window.innerWidth * window.devicePixelRatio;
    c.height = window.innerHeight * window.devicePixelRatio;
    pixelPerMeter = c.height / CANVAS_HEIGHT_AS_METER;
}
handleWindowResize();

function darwBall (sprite, ctx) {
    ctx.save();
    ctx.beginPath();
    ctx.arc(sprite.x, sprite.y, sprite.r, 0, Math.PI * 2, false);
    ctx.clip();

    ctx.shadowColor = 'black';
    ctx.shadowOffsetX = -4;
    ctx.shadowOffsetY = -4;
    ctx.shadowBlur = 7;

    ctx.strokeStyle = '#00bbff';
    ctx.stroke();

    ctx.beginPath();
    ctx.arc(sprite.x, sprite.y, sprite.r / 2, 0, Math.PI * 2, false);
    ctx.clip();

    ctx.shadowColor = 'black';
    ctx.shadowOffsetX = -4;
    ctx.shadowOffsetY = -4;
    ctx.shadowBlur = 7;

    ctx.stroke();
    ctx.restore();
}

var animationTimer = new Sprite.AnimationTimer(3000);

var darwBallPainter = new Sprite.StrokeAndFillPainter(darwBall);

var ball = new Sprite('ball', darwBallPainter);

var ledge = {
    left: c.width / 2 - 100,
    top: c.height / 2 + 300,
    width: 200,
    height: 10,
    draw: function (ctx) {
        ctx.save();
        ctx.fillStyle = 'rgb(255, 100, 100)';
        ctx.fillRect(this.left, this.top, this.width, this.height);
        ctx.restore();
    }
}

function fallDownBehaivor (sprite, behavior, ctx) {
    if(animationTimer.isRunning()) {
        var time = animationTimer.getElapsedTime() / 1000;
        sprite.speed.set({
            x: 0,
            y: pixelPerMeter * GRAVITY_FORCE * time / fps
        })
        sprite.add(sprite.speed);
        if(behavior.hitTest()) {
            sprite.set({
                x: sprite.x,
                y: ledge.top - sprite.r
            })
            animationTimer.stop();
        }
    }
}
ball.addBehavior(fallDownBehaivor, {
    /**
     * 外接矩形碰撞检测
     */
    hitTest: function () {
        var ballRight = ball.x + ball.width,
            ballBottom = ball.y + ball.height,
            ledgeRight = ledge.top + ledge.width,
            nextBallBottomEstimate = ballBottom + ball.speed.y
        return  ballRight > ledge.left &&
                ball.x < ledgeRight &&
                ballBottom < ledge.top &&
                nextBallBottomEstimate > ledge.top;
    }
});

ball.set({
    x: c.width / 2,
    y: 100
});
ball.r = 20;
ball.width = 40;
ball.height = 40;

function loop() {
    ctx.clearRect(0, 0, c.width, c.height);
    requestAnimationFrame(loop);
    var tempFps = stats.update();
    fps = tempFps === 0 ? 60 : tempFps;
    ball.paint(ctx);
    ball.update(ctx);
    ledge.draw(ctx);
}

animationTimer.start();
requestAnimationFrame(loop);